package com.bsoft.gol.hbs.message.sendMsg;

import com.bsoft.gol.hbs.utils.CommonUtils;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevReference;
import hcn.base.Device;
import hcn.base.notification.event.NotificationEvent;
import hcn.bean.PushMessageBean;
import hcn.bean.SendMsgDTO;
import hcn.enums.MsgTemplateCode;
import hcn.enums.MsgType;
import com.bsoft.gol.mpi.provider.IMPIProvider;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import hcn.util.RpcUserToken;
import java.util.Map;

import org.atag.util.common.CopyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import pcn.enums.RoleIdEnum;

/**
 * @description: App推送的消息发送实现-通过极光推送
 * @author: zhengcb10708
 * @create: 2020-09-27 14:15
 **/
@Service
public class AppPushSendMsgServiceByJpush extends AbstractSendMsgServiceImpl {
    private static Logger logger = LoggerFactory.getLogger(AppPushSendMsgServiceByJpush.class);
    @SsdevReference("gol-mpi.mpiProvider")
    private IMPIProvider mpiProvider;

    /**
     * @Describe: 判断是否进行发消息操作-主要进行配置参数的校验
     * @Param: []
     * @Return: boolean
     * @Author: zhengcb10708
     * @Date: 2020/9/27 14:17
     */
    @Override
    protected boolean isDoSendMsg() {
        return true;
    }

   /**
    * @Describe: 发送消息具体实现
    * @Param: [sendMsgDTO, content]
    * @Return: BaseResponse
    * @Author: zhengcb10708
    * @Date: 2020/9/27 14:18
    */
    @Override
    protected BaseResponse doSendMsg(SendMsgDTO sendMsgDTO, String content) {
        BaseResponse baseResponse = new BaseResponse();
            try {
            if (!CommonUtils.isNull(sendMsgDTO.getNotificateType()) || !CommonUtils.isNull(content) ||
            !CommonUtils.isNull(sendMsgDTO.getRoleId())) {
                if(sendMsgDTO!=null&& CommonUtils.isNotNull(sendMsgDTO.getNotificateType())&&CommonUtils.isNull(sendMsgDTO.getTemplateCode())){
                    try{
                        NotificationEvent notificationEvent = new NotificationEvent("标题", NotificationEvent.NotificateType.valueOf(sendMsgDTO.getNotificateType()));
                    }catch (Exception e){
                        logger.error("执行方法messageHandle,NotificateType="+sendMsgDTO.getNotificateType()+",没有对应NotificateType消息枚举");
                        baseResponse.setCode(ResultCode.ERROR);
                        baseResponse.setMessage("传入的NotificateType没有对应的消息枚举名称");
                        return baseResponse;
                    }
                }
                if(sendMsgDTO!=null&&CommonUtils.isNotNull(sendMsgDTO.getTemplateCode())){
                    MsgTemplateCode msgTemplateCode=MsgTemplateCode.get(sendMsgDTO.getTemplateCode());
                    if(CommonUtils.isNull(msgTemplateCode)){
                        logger.error("执行方法messageHandle,TemplateCode="+sendMsgDTO.getTemplateCode()+",没有对应消息编码");
                        baseResponse.setCode(ResultCode.ERROR);
                        baseResponse.setMessage("TemplateCode="+sendMsgDTO.getTemplateCode()+"没有对应的消息编码");
                        return baseResponse;
                    }
                }
                content = deleteStringByDollarSign(content);
                if(RoleIdEnum.DOCTOR.title().equals(sendMsgDTO.getRoleId())){//给医生发送消息
                    sendMsgToDoctor(sendMsgDTO,content);
                }else if(RoleIdEnum.PATIENT.title().equals(sendMsgDTO.getRoleId())){//给患者发送消息
                    sendToPatient(sendMsgDTO,content);
                }
                baseResponse.setCode(ResultCode.SUCCESS);
                baseResponse.setMessage("消息发送成功");
            } else {
                baseResponse.setCode(ResultCode.ERROR);
                baseResponse.setMessage(getName() + "消息发送失败:传入消息参数不全");
            }

        }catch (Throwable throwable){
            throwable.printStackTrace();
            logger.error("消息发送失败,原因:"+throwable.getMessage());
            baseResponse.setCode(ResultCode.ERROR);
            baseResponse.setMessage(getName() + "消息发送失败,原因:"+throwable.getMessage());
        }
        return baseResponse;
    }
    /**
     * @Describe: 发送手工消息推送具体实现
     * @Param: [sendMsgDTO, content]
     * @Return: BaseResponse
     * @Author: zhengcb10708
     * @Date: 2021/9/8 10:50
     */
    @Override
    protected BaseResponse doSendPushMsg(SendMsgDTO sendMsgDTO, String content) {
        logger.info("执行AppPushSendMsgServiceByJpush.doSendPushMsg start");
        BaseResponse baseResponse=new BaseResponse();
        try {
            NotificationEvent notificationEvent =new NotificationEvent(sendMsgDTO.getMsgTitle()==null?"您有一条新的消息通知":sendMsgDTO.getMsgTitle(),NotificationEvent.NotificateType.valueOf(sendMsgDTO.getNotificateType()));
            notificationEvent.setContent(content);
            if(CommonUtils.isNotEmpty(sendMsgDTO.getExtras())){
                for (Map.Entry<String, String> entry : sendMsgDTO.getExtras().entrySet()) {
                    notificationEvent.addExtra(entry.getKey(),entry.getValue());
                }
            }
            if(CommonUtils.isNotEmpty(sendMsgDTO.getBusinessKey())&&sendMsgDTO.getBusinessKey()>0){
                notificationEvent.setBusinessKey(sendMsgDTO.getBusinessKey());
            }
            if (CommonUtils.isNotEmpty(sendMsgDTO.getDeviceList())&&sendMsgDTO.getDeviceList().size() > 0) {
                notificationEvent.setDevices(sendMsgDTO.getDeviceList().toArray(new Device[sendMsgDTO.getDeviceList().size()]));
            }else if(CommonUtils.isNotEmpty(sendMsgDTO.getMpiIds())){
                notificationEvent.setMpiIds(sendMsgDTO.getMpiIds() , RpcUserToken.getTenantId());
            }
            try {
                //MQ发送极光消息
                Client.rpcInvoke("hcn.sendAllKindsMsgService", "productionMessage", CopyUtils.copy(notificationEvent, PushMessageBean.class));
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                throw new ControllerException("发送消息失败，原因:"+throwable.getMessage());
            }
        } catch (ControllerException e) {
            e.printStackTrace();
            baseResponse.setCode(ResultCode.ERROR);
        }
        return baseResponse;
    }

    /**
      * @Describe: 给医生发送即时消息
      * @Param: [sendMsgDTO, content]
      * @Return: void
      * @Author: zhengcb10708
      * @Date: 2020/9/30 13:50
      */
     private void sendMsgToDoctor(SendMsgDTO sendMsgDTO, String content) throws Throwable {

         NotificationEvent notificationEvent =new NotificationEvent(sendMsgDTO.getMsgTitle()==null?"您有一条新的消息通知":sendMsgDTO.getMsgTitle(),NotificationEvent.NotificateType.valueOf(sendMsgDTO.getNotificateType()));

         if(CommonUtils.isNotEmpty(sendMsgDTO.getDoctorIds())){

             if(CommonUtils.isNotEmpty(sendMsgDTO.getTenantIds())){
                 notificationEvent.setDoctorIds(sendMsgDTO.getDoctorIds(), sendMsgDTO.getTenantIds());
             }else if(CommonUtils.isNotNull(sendMsgDTO.getTenantId())){
                 notificationEvent.setDoctorIds(sendMsgDTO.getDoctorIds(), sendMsgDTO.getTenantId());
             }else{
                 notificationEvent.setDoctorIds(sendMsgDTO.getDoctorIds(), RpcUserToken.getTenantId());
             }
         }else if(CommonUtils.isNotEmpty(sendMsgDTO.getMpiIds())){
             notificationEvent.setMpiIds(sendMsgDTO.getMpiIds() ,RpcUserToken.getTenantId());
         }else if(CommonUtils.isNotEmpty(sendMsgDTO.getDeviceList())){
             notificationEvent.setDevices(sendMsgDTO.getDeviceList().toArray(new Device[sendMsgDTO.getDeviceList().size()]));
         }

         if(CommonUtils.isNotEmpty(sendMsgDTO.getExtras())){
             for (Map.Entry<String, String> entry : sendMsgDTO.getExtras().entrySet()) {
                 notificationEvent.addExtra(entry.getKey(),entry.getValue());
             }
         }
         if(CommonUtils.isNotEmpty(sendMsgDTO.getCertificates())&&CommonUtils.isNotEmpty(sendMsgDTO.getTenantIds())){
             notificationEvent.setCertificates(sendMsgDTO.getCertificates(), sendMsgDTO.getTenantIds());
         }
         if(CommonUtils.isNotEmpty(sendMsgDTO.getCards())&&CommonUtils.isNotEmpty(sendMsgDTO.getTenantIds())){
             notificationEvent.setCards(sendMsgDTO.getCards(), sendMsgDTO.getTenantIds());
         }
         if(CommonUtils.isNotEmpty(sendMsgDTO.getBusinessKey())&&sendMsgDTO.getBusinessKey()>0){
             notificationEvent.setBusinessKey(sendMsgDTO.getBusinessKey());
         }
         if(CommonUtils.isNotEmpty(sendMsgDTO.getAffairType())){
             notificationEvent.setAffairType(sendMsgDTO.getAffairType());
         }
         notificationEvent.setContent(content);
         //MQ发送极光消息
         Client.rpcInvoke("hcn.sendAllKindsMsgService", "productionMessage", CopyUtils.copy(notificationEvent, PushMessageBean.class));

     }
     /**
      * @Describe: 给患者发送即时消息
      * @Param: [sendMsgDTO, content]
      * @Return: void
      * @Author: zhengcb10708
      * @Date: 2020/9/30 14:27
      */
     private void sendToPatient(SendMsgDTO sendMsgDTO, String content) throws ControllerException {

             try {
                 NotificationEvent notificationEvent = new NotificationEvent(sendMsgDTO.getMsgTitle()==null?"您有一条新的消息通知":sendMsgDTO.getMsgTitle(), NotificationEvent.NotificateType.valueOf(sendMsgDTO.getNotificateType()));
                 notificationEvent.setContent(content);
                 if(CommonUtils.isNotEmpty(sendMsgDTO.getExtras())){
                     for (Map.Entry<String, String> entry : sendMsgDTO.getExtras().entrySet()) {
                         notificationEvent.addExtra(entry.getKey(),entry.getValue());
                     }
                 }
                 if(CommonUtils.isNotEmpty(sendMsgDTO.getCertificates())&&CommonUtils.isNotEmpty(sendMsgDTO.getTenantIds())){
                     notificationEvent.setCertificates(sendMsgDTO.getCertificates(), sendMsgDTO.getTenantIds());
                 }
                 if(CommonUtils.isNotEmpty(sendMsgDTO.getCards())&&CommonUtils.isNotEmpty(sendMsgDTO.getTenantIds())){
                     notificationEvent.setCards(sendMsgDTO.getCards(), sendMsgDTO.getTenantIds());
                 }
                 if(CommonUtils.isNotEmpty(sendMsgDTO.getBusinessKey())&&sendMsgDTO.getBusinessKey()>0){
                     notificationEvent.setBusinessKey(sendMsgDTO.getBusinessKey());
                 }
                 if(CommonUtils.isNotEmpty(sendMsgDTO.getAffairType())){
                     notificationEvent.setAffairType(sendMsgDTO.getAffairType());
                 }

                 if (CommonUtils.isNotEmpty(sendMsgDTO.getDeviceList())&&sendMsgDTO.getDeviceList().size() > 0) {
                     notificationEvent.setDevices(sendMsgDTO.getDeviceList().toArray(new Device[sendMsgDTO.getDeviceList().size()]));
                  }else if(CommonUtils.isNotEmpty(sendMsgDTO.getMpiIds())){
                     notificationEvent.setMpiIds(sendMsgDTO.getMpiIds() ,RpcUserToken.getTenantId());
                 }
                 try {
                     //MQ发送极光消息
                     Client.rpcInvoke("hcn.sendAllKindsMsgService", "productionMessage", CopyUtils.copy(notificationEvent, PushMessageBean.class));
                 } catch (Throwable throwable) {
                     throwable.printStackTrace();
                     throw new ControllerException("发送消息失败，原因:"+throwable.getMessage());
                 }
             } catch (Exception e) {
                 logger.info("发送消息失败，原因:"+e.getMessage());
                 throw new ControllerException("发送消息失败，原因:"+e.getMessage());
             }
     }
   /**
    * @Describe: 得到具体实现类的名称
    * @Param: []
    * @Return: java.lang.String
    * @Author: zhengcb10708
    * @Date: 2020/9/27 14:18
    */
    @Override
    protected String getName() {
        return MsgType.APP_PUSH.getMsgTypeValue();
    }

    /**
     * @Describe: 获取消息类型
     * @Param: []
     * @Return: java.lang.String
     * @Author: zhengcb10708
     * @Date: 2020/9/27 14:18
     */
    @Override
    public String getMsgType() {
        return MsgType.APP_PUSH.getMsgTypeKey();
    }
}
